<template>
  <app-page>
    <view class="head-box" :style="{ height: `${navHeight}px` }">
      <mxp-navbar :placeholder="true" :showLine="false" titleWidth="0px" :showBack="false" title="">
        <!-- #ifndef MP-TOUTIAO -->
        <template #left>
          <view style="display: flex; flex-direction: row; place-items: center center">
            <image src="@/static/images/logo2.svg" style="width: 30px; height: 30px"></image>
            <text style="font-size: 12px; color: #666666">{{ appInfo?.name || '袋鼠短剧' }}</text>
          </view>
        </template>
        <!-- #endif -->
        <template #right>
          <mxp-search
            background="#ffffff"
            height="30px"
            placeholder="请输入"
            placeholderColor="#998F4B"
            color="#998F4B"
            :cusStyle="{ margin: '15px 0', opacity: 0.6 }"
            :disabled="true"
            @click="onSearch"
          ></mxp-search>
        </template>
      </mxp-navbar>
      <mxp-tabs
        v-model:current="currTabIndex"
        :list="tabList"
        :tabsStyle="{ marginLeft: '30rpx' }"
        width="690rpx"
        activeColor="#fdbe00"
        height="40px"
        lineWidth="40px"
        @change="swiperChange"
      ></mxp-tabs>
    </view>
    <swiper
      :current="currTabIndex"
      :indicatorDots="false"
      :autoplay="false"
      :vertical="false"
      :circular="false"
      class="swiper"
      @change="(event: SwiperOnChangeEvent) => swiperChange(event.detail.current)"
    >
      <swiper-item key="swiper-item-1" class="swiper-item">
        <!-- 占位 -->
        <view :style="{ height: `${navHeight}px` }"></view>
        <mxp-refresh-scroll-view
          ref="chasingRefreshScrollViewRef"
          :height="swiperHeight"
          :style="{ height: swiperHeight, width: '750rpx' }"
          :queryData="queryChasingList"
        >
          <view v-for="(item, index) in myChasingDramaList" :key="index" class="view-record" @click="openVideoDetails(item)">
            <view class="img-box">
              <mxp-image width="180rpx" height="260rpx" borderRadius="12px" errorSize="22px" :src="item.dramaCover"></mxp-image>
            </view>
            <view style="display: flex; flex: 1; flex-direction: column; justify-content: center; width: 100%; padding-left: 15px">
              <view class="record-title-box">
                <text class="record-title">{{ item.dramaTitle }}</text>
              </view>
              <view style="display: flex; flex-direction: column; justify-content: space-between">
                <view class="record-info-box">
                  <text class="intro record-info">简介: {{ item.dramaDesp || '' }}</text>
                </view>
                <view class="record-info-box-seq">
                  <view class="seq">
                    <view>
                      <text class="have-see record-info">已看 {{ item.episodeSeq }} 集</text>
                      <text class="record-info total">&nbsp;/ 共 {{ item.seqNum }} 集</text>
                    </view>
                    <view class="schedule">
                      <view class="actual" :style="{ right: `${100 - (item.episodeSeq / item.seqNum) * 100}%` }"></view>
                    </view>
                  </view>
                  <view class="butt-box">立即观看</view>
                </view>
              </view>
            </view>
          </view>
        </mxp-refresh-scroll-view>
      </swiper-item>
      <swiper-item key="swiper-item-2" class="swiper-item">
        <!-- 占位 -->
        <view :style="{ height: `${navHeight}px` }"></view>
        <mxp-refresh-scroll-view
          ref="watchRefreshScrollViewRef"
          :height="swiperHeight"
          :style="{ height: swiperHeight, width: '750rpx' }"
          :queryData="queryWatchList"
        >
          <view v-for="(item, index) in watchRecordList" :key="index" class="view-record" @click="openVideoDetails(item)">
            <view class="img-box">
              <mxp-image width="180rpx" height="260rpx" borderRadius="12px" errorSize="22px" :src="item.dramaCover"></mxp-image>
            </view>
            <view style="display: flex; flex: 1; flex-direction: column; justify-content: center; width: 100%; padding-left: 15px">
              <view class="record-title-box">
                <text class="record-title">{{ item.dramaTitle }}</text>
              </view>
              <view style="display: flex; flex-direction: column; justify-content: space-between">
                <view class="record-info-box">
                  <text class="intro record-info">简介: {{ item.dramaDesp || '' }}</text>
                </view>
                <view class="record-info-box-seq">
                  <view class="seq">
                    <view>
                      <text class="have-see record-info">观看至 {{ item.episodeSeq }} 集</text>
                      <text class="record-info total">&nbsp;/ 共 {{ item.seqNum }} 集</text>
                    </view>
                  </view>
                  <view class="butt-box">立即观看</view>
                </view>
              </view>
            </view>
          </view>
        </mxp-refresh-scroll-view>
      </swiper-item>
    </swiper>
  </app-page>
</template>

<script setup lang="ts">
  import { computed, ref, watch } from 'vue';
  import AppPage from '@/components/app-page/app-page.vue';
  import MxpTabs, { type $TabsItem } from '@/mxp-ui/mxp-tabs/mxp-tabs.vue';
  import MxpNavbar from '@/mxp-ui/mxp-navbar/mxp-navbar.vue';
  import MxpRefreshScrollView, { type Ins } from '@/mxp-ui/mxp-refresh-scroll-view/mxp-refresh-scroll-view.vue';
  import mxpGetSysInfoStore from '@/mxp-ui/mxp-tool/store/mxp-store-sys-info';
  import { getAppInfo } from '@/config/mp-config';
  import { getHeaderHeight } from '@/mxp-ui/mxp-tool/utils/dom';
  import MxpSearch from '@/mxp-ui/mxp-search/mxp-search.vue';
  import type { $AllSizeUnitStr } from '@/mxp-ui/mxp-tool/types/interface';
  import { type MyChasingDrama, type WatchDrama, myChasingDramaListAxios, watchDramaRecordsListAxios } from '@/api/drama';
  import MxpImage from '@/mxp-ui/mxp-image/mxp-image.vue';
  import type { SwiperOnChangeEvent } from 'mxp-uni-types';
  import { openPlayletPage } from '@/utils/page/rest';
  import { useAppStore } from '@/pinia/app';
  import { onShow } from '@dcloudio/uni-app';
  import { autoLogin } from '@/utils/page/user';

  const tabList: ($TabsItem & { state: 0 | 1 | 2 })[] = [
    { label: '我的追剧', state: 0 },
    { label: '我的观看', state: 1 },
  ];
  const appInfo = getAppInfo();
  const sys = mxpGetSysInfoStore().getSysInfo();
  const currTabIndex = ref(0);
  const myChasingDramaList = ref<MyChasingDrama[]>([]);
  const watchRecordList = ref<WatchDrama[]>([]);
  const watchRefreshScrollViewRef = ref<InstanceType<typeof MxpRefreshScrollView>>();
  const chasingRefreshScrollViewRef = ref<InstanceType<typeof MxpRefreshScrollView>>();

  /** 登录状态 */
  const loginState = computed(() => useAppStore().loginState);
  let init = false; // 用于仅在返回时才刷新

  watch(
    () => loginState.value,
    (state) => {
      init && state && watchRefreshScrollViewRef.value?.initLoadRefresh();
      init && state && chasingRefreshScrollViewRef.value?.initLoadRefresh();
    }
  );

  onShow(() => {
    init && watchRefreshScrollViewRef.value?.initLoadRefresh();
    init && chasingRefreshScrollViewRef.value?.initLoadRefresh();
  });

  /** 高度 */
  const navHeight = computed(() => (sys.value.statusBarHeight || 0) + getHeaderHeight(sys.value.statusBarHeight) + 40);
  /** 高度 */
  const swiperHeight = computed<$AllSizeUnitStr>(() => {
    let h = sys.value.windowHeight - navHeight.value;
    // #ifdef MP-TOUTIAO
    h = h + (sys.value.statusBarHeight || 0) + getHeaderHeight(sys.value.statusBarHeight);
    // #endif
    return `${h}px`;
  });

  /** 改变 */
  function swiperChange(index: number) {
    currTabIndex.value = index;
  }

  /**
   * 获取追剧记录
   */
  async function queryChasingList(ins: Ins) {
    init = false;
    try {
      try {
        // 如果未登录先静默登录
        !loginState.value && (await autoLogin());
      } catch (error) {}
      const res = await myChasingDramaListAxios(ins.page, ins.size);
      myChasingDramaList.value = ins.page > 1 ? myChasingDramaList.value.concat(res.data.records) : res.data.records;
      ins.setMoreSuccess(res.data.records.length, res.data.total);
      init = false;
    } catch (error) {
      init = false;
      ins.setMoreEmpty('fail_load', error.msg || '获取数据失败，BD001');
    }
  }

  /**
   * 获取观看记录
   */
  async function queryWatchList(ins: Ins) {
    init = false;
    try {
      try {
        // 如果未登录先静默登录
        !loginState.value && (await autoLogin());
      } catch (error) {}
      const res = await watchDramaRecordsListAxios(ins.page, ins.size);
      watchRecordList.value = ins.page > 1 ? watchRecordList.value.concat(res.data.records) : res.data.records;
      ins.setMoreSuccess(res.data.records.length, res.data.total);
      init = true;
    } catch (error) {
      ins.setMoreEmpty('fail_load', error.msg || '获取数据失败，BD001');
      init = true;
    }
  }

  /** 搜索 */
  function onSearch() {
    uni.navigateTo({ url: `/pages/drama/drama-search/drama-search` });
  }

  /** 打开视频详情 */
  function openVideoDetails(item: MyChasingDrama) {
    openPlayletPage(item);
  }
</script>

<style lang="scss" scoped>
  .head-box {
    position: fixed;
    top: 0;
    z-index: 222;
    width: 100vw;
    height: 84px;
    background: #f8f8f8;
  }

  .swiper {
    width: 100%;
    height: 100vh;
    overflow: hidden;

    .swiper-item {
      width: 100%;
      height: 100vh;
      overflow: hidden;
    }
  }

  .view-record {
    position: relative;
    display: flex;
    width: 690rpx;
    padding-top: 15px;
    margin-left: 30rpx;
    vertical-align: top;

    .record-title-box {
      width: 100%;

      .record-title {
        overflow: hidden;
        font-size: 30rpx;
        font-weight: bold;
        color: #000000;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .record-info-box {
      display: flex;
      flex-direction: row;
      justify-content: space-between;

      .record-info {
        font-size: 24rpx;
        text-align: justify;
      }

      .intro {
        display: -webkit-box;
        padding-top: 20rpx;
        overflow: hidden;
        color: #999999;
        word-break: break-all;
        -webkit-line-clamp: 3;
        line-clamp: 3;
        -webkit-box-orient: vertical;
      }
    }

    .record-info-box-seq {
      display: flex;
      justify-content: space-between;
      margin-top: 8px;
      font-size: 24rpx;

      .seq {
        display: flex;
        flex-direction: column;
        gap: 10rpx;
        justify-content: center;
        width: 60%;

        .schedule {
          position: relative;
          height: 8rpx;
          background-color: #dddddd;
          border-radius: 4rpx;

          .actual {
            position: absolute;
            left: 0;
            height: 100%;
            background: linear-gradient(to right, #fdbe00 0%, #f66f00 100%);
            border-radius: 4rpx;

            &:after {
              position: absolute;
              top: -2rpx;
              right: -2rpx;
              width: 12rpx;
              height: 12rpx;
              content: '';
              background-color: #ffffff;
              border-radius: 50%;
              box-shadow: 0 0 6rpx #999999;
            }
          }
        }

        .total {
          color: #999999;
        }
      }

      .butt-box {
        flex-shrink: 0;
        padding: 6px 10px;
        font-size: 22rpx;
        color: #ff6e25;
        background: #ffeee5;
        border-radius: 4px;
      }
    }
  }
</style>
